﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.IO;

namespace SimpleServerWarp
{
    class LogHandler
    {
        static LogHandler()
        {
            Thread t = new Thread(ExcuteWrite);
            _today = DateTime.Now.Date;
            _logFileName = string.Format(@"{0}\{1}.exeption_log.txt", AppDomain.CurrentDomain.BaseDirectory,
                _today.ToString("yyyyMMdd"));
            t.IsBackground = true;
            t.Start();
        }

        static DateTime _today;
        static string _logFileName;

        static readonly Queue<string> Errors = new Queue<string>();

        static readonly object LogLock = new object();

        private static void ExcuteWrite()
        {
            while (true)
            {
                try
                {
                    if (Errors != null && Errors.Count > 0)
                    {
                        string errorLogInfo = String.Empty;
                        lock (LogLock)
                        {
                            errorLogInfo = Errors.Dequeue();
                        }
                        DateTime dt = DateTime.Now.Date;
                        if (dt != _today)
                        {
                            _today = dt;
                            _logFileName = string.Format(@"{0}\{1}.exeption_log.txt",
                                AppDomain.CurrentDomain.BaseDirectory, _today.ToString("yyyyMMdd"));
                        }
                        if (!string.IsNullOrEmpty(errorLogInfo))
                        {
                            File.AppendAllText(_logFileName, errorLogInfo);
                        }
                    }
                    else
                    {
                        Thread.Sleep(500);
                    }
                }
                catch
                {

                }
            }
        }

        public static void Handle(Exception ex,string describle = null)
        {
            StringBuilder sb = new StringBuilder();
            string dt = DateTime.Now.ToString();
            if (!string.IsNullOrEmpty(describle))
            {
                sb.Append(describle);
                sb.Append("------\r\n");
            }
            sb.Append(dt)
                .Append("\r\n内部错误:")
                .Append(ex.InnerException != null ? ex.InnerException.ToString() : "")
                .Append("\r\n堆栈:")
                .Append(ex.StackTrace != null ? ex.StackTrace : "")
                .Append("\r\n内容:")
                .Append(ex.Message != null ? ex.Message : "")
                .Append("\r\n来源:").Append(ex.Source != null ? ex.Source : "").Append("\r\n");
            lock (LogLock)
            {
                Errors.Enqueue(sb.ToString());
            }
        }
    }
}

